"""
项目管理模块
负责项目数据的模型定义、文件操作和业务逻辑
"""

import json
import os
from typing import List, Dict, Any, Optional
from pydantic import BaseModel

# 项目数据文件路径
PROJECTS_FILE = os.path.join(os.path.dirname(__file__), "projects", "projects.json")

class TestItems(BaseModel):
    门控: bool = False
    开门时间: bool = False
    关门时间: bool = False
    最大力: bool = False
    拉力: bool = False
    软件版本: bool = False
    耐压: bool = False
    塞拉力: bool = False
    推力: bool = False

class ProductItem(BaseModel):
    产品名称: str
    测试项: TestItems

class ProjectData(BaseModel):
    id: Optional[int] = None
    项目编号: str
    项目名称: str
    产品: List[ProductItem] = []

def load_projects() -> List[Dict[str, Any]]:
    """从JSON文件加载项目数据"""
    try:
        if os.path.exists(PROJECTS_FILE):
            with open(PROJECTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []
    except Exception as e:
        print(f"加载项目数据失败: {e}")
        return []

def save_projects(projects: List[Dict[str, Any]]) -> bool:
    """保存项目数据到JSON文件"""
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(PROJECTS_FILE), exist_ok=True)
        
        with open(PROJECTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(projects, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存项目数据失败: {e}")
        return False